package top.csmcool.musicapi.resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import top.csmcool.musicapi.domain.ResourceUrl;
import top.csmcool.musicapi.enums.PlatformEnum;
import top.csmcool.musicapi.service.ResourceUrlService;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 请求地址资源获取
 * @Description
 * @Author shizhe
 * @Date 2025/2/8
 */

@Component
@RequiredArgsConstructor
public class MusicUrlResource {

    private final ResourceUrlService resourceUrlService;
    private final Map<String, ResourceUrl> resourceUrlMap = new ConcurrentHashMap<>();
    private final Object lock = new Object(); // 锁对象
    /**
     * @param method 方法名
     * @param platformEnum 平台枚举
     * @return 请求地址
     */

    public String getResourceUrl(String method, PlatformEnum platformEnum) {
        synchronized (lock) {
            if (resourceUrlMap.isEmpty()) {
                QueryWrapper<ResourceUrl> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("is_common", 1);
                queryWrapper.eq("user_id", null);
                List<ResourceUrl> resourceUrls = null;
                try {
                    resourceUrls = resourceUrlService.list(queryWrapper);
                    resourceUrls.forEach(resourceUrl ->
                            {
                                String key = resourceUrl.getPlatform() + "_" + resourceUrl.getMethod();
                                resourceUrlMap.put(key, resourceUrl);
                            }
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // 避免空指针
        String key = platformEnum + "_" + method;
        ResourceUrl resourceUrl = resourceUrlMap.getOrDefault(key, new ResourceUrl());
        return resourceUrl.getUrl();
    }
}
